package com.zm.se.service.EquService.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zm.se.entity.*;
import com.zm.se.listenner.EquExcelListener;
import com.zm.se.mapper.EquipmentMapper.EquMapper;
import com.zm.se.mapper.managerMapper.ManagerMapper;
import com.zm.se.service.EquService.IEquService;
import com.zm.se.service.EquService.ex.BorrowException;
import com.zm.se.service.EquService.ex.CheckException;
import com.zm.se.service.EquService.ex.ReturnOutofNumberException;
import com.zm.se.service.EquService.ex.UnderStockException;
import com.zm.se.service.managerService.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class EquServiceImpl implements IEquService {

    private Equipment equipmentOriginal;
    @Autowired
    EquMapper mapper;
    @Autowired
    ManagerMapper managerMapper;


    public Integer initDataInMysql(){


        //清空原有供应商表
        mapper.truncatesup();
        //生成供应商表
        //获取生成供应商表的参数信息
        List<Map> supList=mapper.showsup();
        for (Map supMap : supList) {
            String sup=supMap.get("sup").toString().trim();
            System.out.println(sup);
            String phone=supMap.get("phone").toString().trim();
            System.out.println(phone);
            String address=supMap.get("address").toString().trim();
            String email=supMap.get("email").toString().trim();
            System.err.println(supMap);
            //向供应商表中插入信息
            System.out.println("供应商表生成"+ mapper.ordersup(sup,phone,address,email));
        }

        mapper.truncatePrice();
        List<Map> list=mapper.showprice();
        for (Map map : list) {
            System.err.println(map);
            String ename=map.get("ename").toString().trim();
            double price=Double.parseDouble(map.get("price").toString().trim()) ;
            String sup=map.get("sup").toString().trim();
            System.out.println(mapper.insertPrice2(ename,price,sup));
        }
        //清空原有器材整理表
        mapper.truncateorderequ();
        //生成整理器材表
        //获取生成理器材表的参数信息
        List<Map> equList=mapper.showlist();
        System.out.println(equList);
        for (Map equMap : equList) {
            System.err.println(equMap.get("ename"));
            System.err.println(equMap.get("enumber"));

            String ename= (String) equMap.get("ename");
            Integer enumber= Integer.parseInt(equMap.get("enumber").toString().trim());
            String unit=(String)equMap.get("unit");
            //向整理器材表中插入信息
            System.out.println("器材整理表生成"+mapper.orderdatabase(ename,enumber,unit));
        }
        //获取到借出表中的各种器材的借出总量，然后从新器材整理表中减去
        List<Map> borrowList=mapper.borrowsum();
        for (Map map : borrowList) {
            for (Map equMap : equList) {
                //新器材整理表中的器材数
                Integer orderEnumber= Integer.parseInt(equMap.get("enumber").toString().trim());
                //借用记录表中的个器材名
                String borrowEname= map.get("ename").toString();
                //借用记录表中器材数量
                Integer borrowEnumber= Integer.parseInt(map.get("enumber").toString().trim());
                System.err.println(borrowEname);
                System.err.println(borrowEnumber);
                //修改表的值
                //用新整理表中的总数减去已经借用的，就成了新录入后剩余的
                System.out.println(mapper.updateOrderEqu(borrowEname,(orderEnumber-borrowEnumber)));
            }

        }
        System.out.println("开始摘取采购表数据");
        //获取采购表信息，并根据ename将对应器材的数量减少到库存真实值
        List<Scrap> purchaseList=mapper.PurchaseList();
        System.err.println(purchaseList);
        for (Scrap scrap : purchaseList) {
            String ename= scrap.getEname();
            Integer enumber=mapper.findEnumberByEname(scrap.getEname());
            int updatenumber=enumber-scrap.getEnumber();
            System.out.println("测试：：：：："+updatenumber);

            System.err.println("测试执行"+mapper.updateOrderEqu(ename,updatenumber));
            System.out.println("测试success");
        }

        return 1;
    }
    /**
     * 录入excel器材表后生成一系列表
     * @param path excel表保存路径
     * @param filename excel表保存名
     * @return
     */

    @Override
    public int ExcelReadEqu(String path, String filename) {
        int begin = mapper.selectCount(equipmentOriginal);
        System.err.println("begin"+begin);
        //                                                文件路径         读出类型          监听器
        ExcelReader reader= EasyExcel.read(path+filename, Equipment.class,new EquExcelListener(mapper)).build();
        ReadSheet build = EasyExcel.readSheet(0).build();
        System.err.println(build);
        reader.read(build);
        reader.finish();
        int end = mapper.selectCount(equipmentOriginal);
        System.err.println("end"+end);
        System.err.println("录入成功");

        if (initDataInMysql()==1){
            System.out.println("初始化成功");
        }
        return 1;
    }

    @Override
    public int addPurchase(Purchase purchase,String manager) {
        List<Purchase> list=mapper.selectAllPurchase();
        for (Purchase purchase1 : list) {
            if (purchase.getEname().equals(purchase1.getEname())){
                //存在了，失败，前端提示，记录中已存在该器材的记录，修改即可
               return 0;
            }
        }
        purchase.setCreatedTime(new Date());
        purchase.setCreatedUser(manager);
        return mapper.addPurchase(purchase);
    }


    /**
     *  添加借用记录
     * @param empname   借用人姓名
     * @param empnum    借用人工号
     * @param ename 借用器材名
     * @param enumber   借用器材数量
     * @param managernum   当值管理员工号，用于查找姓名
     * @return
     */
    @Override
    public void empborrow(String empname, String empnum, String ename, Integer enumber, String managernum) {
         if (empname==null||empnum==null){
             throw new CheckException("验证信息丢失，请返回重新验证");
         }
         if(ename==null||enumber==0){
             throw new BorrowException("申请信息不可为空，请重新填写");
         }
        System.err.println("验证通过");
         //判断库存是否足够
        //库存数量为
        Integer n=mapper.findEnumberByEname(ename);
        System.err.println(n);
        if (enumber>n){
            throw new UnderStockException("库存不足");
        }
        System.err.println("库存充足");
         //补全信息
         Borrow borrow=new Borrow();
         borrow.setEmpname(empname);
         borrow.setEmpnum(empnum);
         borrow.setEname(ename);
         borrow.setEnumber(enumber);

         borrow.setCreatedUser(managerMapper.findByNum(managernum).getUsername());
         borrow.setCreatedTime(new Date());
         borrow.setModifiedTime(new Date());
         borrow.setModifiedUser(managerMapper.findByNum(managernum).getUsername());
         System.err.println(mapper.borrow(borrow));
         //修改整理器材表中的信息减去显影数量的器材
        System.err.println(mapper.updateOrderEqu(ename,(n-enumber)));
        System.err.println("库存剩余"+mapper.findEnumberByEname(ename));
    }

    /**
     * 器材归还
     * @param id
     * @param newNumber
     */
    @Override
    public void empreturn(Integer id,Integer newNumber,String manager) {
        System.err.println("归还方法执行");
        Borrow borrow=mapper.findById(id);

        System.err.println(borrow);
        Integer oldNumber=borrow.getEnumber();
        if(oldNumber>newNumber){
            Integer enumber=oldNumber-newNumber;
            //修改借用器材记录的数量，和修改人，修改时间
            Borrow borrowChange=new Borrow();
            borrowChange.setId(id);
            borrowChange.setEnumber(enumber);
            borrowChange.setModifiedUser(manager);
            borrowChange.setModifiedTime(new Date());
            mapper.updateBorrow(borrowChange);
            //将归还数量返回至器材整理表
            String ename=borrow.getEname();
            //库存数量为
            Integer n=mapper.findEnumberByEname(ename);
            System.err.println("库存数量"+n);
            System.err.println("还的数量"+newNumber);
            Integer returnnumber=n+newNumber;
            System.err.println( mapper.updateOrderEqu(ename,returnnumber));
            System.err.println("剩余"+enumber+"尚未归还");
        }else if (oldNumber==newNumber){
            mapper.delBorrow(id);
//将归还数量返回至器材整理表
            String ename=borrow.getEname();
            //库存数量为
            Integer n=mapper.findEnumberByEname(ename);
            System.err.println("库存数量"+n);
            System.err.println("还的数量"+newNumber);
            Integer returnnumber=n+newNumber;
            System.err.println( mapper.updateOrderEqu(ename,returnnumber));
            System.err.println("该记录已删除");
        }else if (oldNumber<newNumber){
            throw new ReturnOutofNumberException("归还数量大于申请数量，请核实后再归还");
        }
        System.err.println("归还方法结束");
    }

    /**
     * 报废处理
     * @param ename
     * @param enumber
     * @param price
     * @param sup
     */
    @Override
    public void addScrap(String ename, Integer enumber, Integer price, String sup,String manager) {
        System.err.println("保存记录添加执行");
        //向scrap表和scrapnote表中擦汗如数据
        Scrap scrap=new Scrap();
        scrap.setEname(ename);
        scrap.setEnumber(enumber);
        scrap.setPrice(price);
        scrap.setSup(sup);
        scrap.setCreatedUser(manager);
        scrap.setCreatedTime(new Date());
        //再从器材整理表中删除保费器材的数量
        //查询该器材的总数
        Integer n=mapper.findEnumberByEname(ename);
        //总数减去enumber，修改给器材整理表
        Integer scrapNumber=n-enumber;
        //向scrap表中插入
        if (mapper.insertScrap(scrap)!=1||!mapper.updateOrderEqu(ename,scrapNumber)){
            throw new InsertException("报废信息插入失败请重试");
        }
        System.err.println("保存记录添加完成");
        System.err.println("正在清理更改前的采购表");
        System.err.println(mapper.truncatepurchase());
        System.err.println("清理完成");
        System.err.println("正在生成修改后的采购表");
        List<Scrap> scrapList=mapper.PurchaseList();
        for (Scrap scrap1 : scrapList) {
            //将数据插入到采购表中
            if ( mapper.insertPurchase(scrap1)==1){
                System.out.println("插入成功");

            }else {
                System.err.println("向采购表插入信息失败");
                throw new InsertException("操作过程失败请联系管理员");
            }
        }
        System.err.println("生成完毕");

    }

    @Override
    public Integer scrapupdate(Integer id, String ename, Integer enumber, String sup,String manager){
        System.err.println("scrapupdate");
        System.err.println("id: "+id+" sup: "+sup+"  name:  "+ename+" number: "+enumber);
        //判断输入数量是否与记录中的数量关系
        Integer noteEnumber=mapper.findScrapById(id).getEnumber();
        System.out.println("noteEnumber"+noteEnumber);

        Integer ordernumber=mapper.findEnumberByEname(ename);
        System.out.println("ordernumber"+ordernumber);

        Integer changenum=ordernumber+(noteEnumber-enumber);
        System.out.println("changenum"+changenum);
        int updatenum=ordernumber+noteEnumber;
        if (0==enumber){
            System.err.println(mapper.delScrap(id));
            System.err.println("修改器材整理表："+ mapper.updateOrderEqu(ename,updatenum));

            System.err.println("删除成功");
            }
        if (noteEnumber>enumber){
            //修改记录
            //删除再添加
            //删除
            if(mapper.delScrap(id)==1){
                System.err.println("删除成功");
                Scrap s=new Scrap();
                s.setEname(ename);
                s.setEnumber(enumber);
                s.setSup(sup);
                s.setPrice(mapper.selectPriceByEnameSup(ename,sup));
                s.setCreatedTime(new Date());
                s.setCreatedUser(manager);
                if (mapper.insertScrap(s)==1){
                    System.err.println("插入成功");
                    if(mapper.updateOrderEqu(ename,changenum)){
                        System.err.println("器材整理表修改完成");
                    }
                }

            }
        }
        System.err.println("正在清理更改前的采购表");
        System.err.println(mapper.truncatepurchase());
        System.err.println("清理完成");
        System.err.println("正在生成修改后的采购表");
        List<Scrap> scrapList=mapper.PurchaseList();
        for (Scrap scrap : scrapList) {
            //将数据插入到采购表中
            if ( mapper.insertPurchase(scrap)!=1){
                System.err.println("向采购表插入信息失败");
                throw new InsertException("操作过程失败请联系管理员");
            }
        }
        System.err.println("生成完毕");
        return 1;
    }

    //输出路径
    String PATH="C:\\Users\\zm\\Desktop\\";
    @Override
    public void outputScrapExcel() {
        //向采购表中插入数据
        //获取scrap表中的数据（器材名和对应的器材数）
        //数据
        List<Purchase> list= mapper.selectAllPurchase();
        //建工作簿
        ExcelWriter writer= EasyExcel.write(PATH+"采购表.xls", Purchase.class).build();
        //建工作i表
        WriteSheet sheet= EasyExcel.writerSheet("采购表").build();
        //写入
        writer.write(list,sheet);
        //关闭
        writer.finish();
        System.out.println("导出完毕");

        System.err.println("正在清理更改前的采购表");
        System.err.println(mapper.truncatepurchase());
        System.err.println("清理完成");
    }

    /**
     * 采购表修改
     * @param id
     * @param ename
     * @param enumber
     * @param unit
     * @param manager
     * @return
     */
    @Override
    public Integer purchasepdate(Integer id, String ename, Integer enumber, String unit, String manager) {
        if (enumber==0){
            System.out.println(mapper.delPurchase(id));
            return 1;
        }
        System.err.println("purchasepdate");
        System.err.println(mapper.findPurchaseById(id));
        Purchase purchase=new Purchase();
        purchase.setEnumber(enumber);
        purchase.setId(id);
        purchase.setUnit(unit);
        purchase.setCreatedUser(manager);
        purchase.setCreatedTime(new Date());
        System.err.println(purchase);
        System.err.println(mapper.updatePurchase(purchase));
        System.err.println("修改采购表成功");
        System.err.println(mapper.findPurchaseById(id));
        return 1;
    }

    @Override
    public Integer delEmp(Integer id) {
      if ( managerMapper.delEmp(id)==1){
          if (initDataInMysql()==1){
              System.out.println("初始化成功");
          }
        }
        return 1;
    }

    @Override
    public Integer delEqu(Integer id) {
       if ( mapper.delEqu(id)==1){
            if (initDataInMysql()==1){
                System.out.println("初始化成功");
            }
        }
        return 1;
    }

    @Override
    public Integer updateEmp(Emp emp) {
       if (managerMapper.updateEmp(emp)==1){
           if (initDataInMysql()==1){
               System.out.println("初始化成功");
           }
       }else {
           System.out.println("失败");
           return 0;
       }
        return 1;
    }

    @Override
    public Integer updateEqu(Equipment equipment) {

        if (mapper.updateEqu(equipment)==1) {
            if (initDataInMysql() == 1) {
                System.out.println("初始化成功");
            }
        }else {
            System.out.println("失败");
            return 0;
        }
        return 1;
    }

    @Override
    public Integer addEqu(Equipment equipment) {
        if (equipment.getEname()==null
                ||equipment.getEnumber()==null
                ||equipment.getEmail()==null
                ||equipment.getAddress()==null
                ||equipment.getPhone()==null
                ||equipment.getSup()==null
                ||equipment.getPrice()==0.0){
            throw new InsertException("请将信息填写完整再试");
        }else if (mapper.InsertEqu(equipment)!=1){
            return 0;
        }else {
            return 1;
        }

    }

    @Override
    public Integer addEmp(Emp emp) {
        if (emp.getUsername()==null
                ||emp.getAge()==null
                ||emp.getSex()==null
                ||emp.getPhone()==null
                ||emp.getNum()==null
                ||emp.getEmail()==null){
            throw new InsertException("请将信息填写完整再试");
        }else if(managerMapper.InsertTeacher(emp)!=1){
            return 0;
        }else {
            return 1;
        }
    }


}
